package com.monkeyboy.mongo_demo;

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.model.Filters;
import com.monkeyboy.util.MongoDBAuthUtil;
import org.bson.Document;
import org.bson.types.ObjectId;

import javax.print.Doc;

/**
 * 分页查询
 *
 * @Author Gavin
 * @date 2021.01.11 16:20
 */
public class SelectDocumentByPage {
    public static void main(String[] args) {
        SelectDocumentByPage selectDocumentByPage = new SelectDocumentByPage();
//        selectDocumentByPage.selectDocumentByPage(1, 1);
        selectDocumentByPage.selectDocumentByPageUseCondition(2, 2, "5ff72b0635d152b587b6dbab");
    }

    /**
     * 通过条件判断优化分页
     */
    public void selectDocumentByPageUseCondition(int indexPage, int limit, String lastId) {
        MongoCollection<Document> collection = MongoDBAuthUtil.getCollection("test", "java_coll");
        //返回满足条件的总条数
        Document condition = new Document();
        long count = collection.countDocuments(condition);
        FindIterable<Document> documents = null;
        if (indexPage == 1) {
            documents = collection.find(condition).limit(limit);
        } else {
            if (lastId != null) {
                condition.append("_id", new Document("$gt", new ObjectId(lastId)));
                documents = collection.find(condition).limit(limit);
            }
        }
        //通过游标来访问数据
        MongoCursor<Document> cursor = documents.iterator();
        while (cursor.hasNext()) {
            Document doc = cursor.next();
            System.out.println(doc.get("username") + "\t" + doc.get("tags") + "\t" + doc.get("age"));
        }
    }

    /**
     * 通过skip和limit实现分页
     * 数据量大的时候不建议使用skip limit的方式进行分页
     */
    public void selectDocumentByPage(int indexPage, int limit) {
        int page = (indexPage - 1) * limit;
        MongoCollection<Document> collection = MongoDBAuthUtil.getCollection("test", "java_coll");
        //返回满足条件的总条数
        Document condition = new Document();
        condition.put("username", "test");
        long count = collection.countDocuments(condition);
        // long count = collection.countDocuments(Filters.eq("username","test"));
//        Document condition2=new Document("age",new Document("$ne",null));
        System.out.println(count);
        //返回文档的一个迭代器
        //in第一个参数为键，后面的值作为值
        FindIterable<Document> documents = collection.find(condition).sort(new Document("age", 1)).skip(page).limit(limit);
        //通过游标来访问数据
        MongoCursor<Document> cursor = documents.iterator();
        while (cursor.hasNext()) {
            Document doc = cursor.next();
            System.out.println(doc.get("username") + "\t" + doc.get("tags") + "\t" + doc.get("age"));
        }
    }
}
